from django.shortcuts import render
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from goods.models import SKU
from goods.serializers import ListSerializer, SKUIndexSerializer
from meiduo_mall.utils.pagination import StandardPagination


# # /categories/(?P<category_id>\d+)/skus/?page=页码&page_size=页容量&ordering=排序字段
# class ListView(GenericAPIView):
#     """列表页"""
#     serializer_class = ListSerializer
#
#     def get_queryset(self):
#         category_id = self.kwargs['category_id']
#         return SKU.objects.filter(category=category_id)
#
#     def get(self, request, category_id):
#         # 根据分类ＩＤ查询SKU
#         # skus = SKU.objects.filter(categories_id=categories_id)
#         skus = self.get_queryset()
#         # 序列化输出
#         serializer = self.get_serializer(skus, many=True)
#
#         return Response(serializer.data)


# /categories/(?P<category_id>\d+)/skus/?page=页码&page_size=页容量&ordering=排序字段
class ListView(ListAPIView):
    """列表页优化"""
    serializer_class = ListSerializer
    # 分页
    pagination_class = StandardPagination
    # 排序
    filter_backends = [OrderingFilter]
    ordering_fields = ('create_time', 'sales', 'price')

    # 127.0.0.1:8000/books/?ordering=-bread

    def get_queryset(self):
        category_id = self.kwargs['category_id']
        return SKU.objects.filter(category=category_id)


class SKUSearchViewSet(HaystackViewSet):
    """搜索视图"""
    # 指定索引的模型类
    index_models = [SKU]

    # 指定搜索结果使用的序列化器类
    # haystack的每个结果中都包含两个属性
    # text: 索引字段
    # object:搜索出的模型对象
    serializer_class = SKUIndexSerializer
